const { Transform } = require('stream');
const request = require('request');
const p = require('path');
const fs = require('fs-extra');
const moment = require('moment');
const _ = require('lodash');
const utils = require('../../utils');

async function download(url, path) {
  return new Promise(resolve => {
    if (!/^https?:\/\//.test(url)) {
      return resolve(url);
    }
    const extname = /png/.test(url) ? 'png' : 'jpg';
    const fullname = p.join(path, `${utils.uuid()}.${extname}`).replace(/\\/g, '/');
    request(url).pipe(fs.createWriteStream(fullname)).on('close', function() {
      resolve(fullname);
    }).on('error', function(e) {
      resolve(url);
    });
  });
}
module.exports = function ({ urlName = 'url', path = '.', inFormat, outFormat } = {}) {
  const stream = new Transform({ objectMode: true });
  inFormat = utils.parseFunction(inFormat);
  outFormat = utils.parseFunction(outFormat);
  const errorList = [];
  fs.ensureDirSync(path);
  stream._transform = async function (chunk, _encoding, callback) {
    utils.debug('imageSaveTransform [chunk]:', chunk);
    const params = inFormat ? await inFormat(chunk, { _, moment, utils }) : chunk;
    if (!params[urlName]) {
      stream.push(params);
      return callback();
    }
    const newUrl = await download(params[urlName], path);
    params[urlName] = newUrl;
    stream.push(params);
    callback();
  };
  stream.on('finish', function () {
    errorList.length && console.error('imageSaveTransform [error]:', errorList);
    utils.debug('imageSaveTransform [finish]');
  });

  return stream;
};